package com.app.utils.spring.datasource;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 动态数据源切换处理器
 */
@Aspect
@Component
@Order(1)  // 该切面应当先于 @Transactional 执行
public class DynamicDataSourceAspect {

    /**
     * 切换数据源
     * @param point
     * @param dataSource
     */
    @Before("@annotation(dataSource))")
    public void switchDataSource(JoinPoint point, DataSourceBy dataSource) {
        if (!DynamicDataSourceContextHolder.containDataSourceKey(dataSource.value())) {
            System.out.println("DataSource [{}] doesn't exist, use default DataSource [{}] " + dataSource.value());
        } else {
            // 切换数据源
            String old = DynamicDataSourceContextHolder.getDataSourceKey();
            if(!old.equals(dataSource.value())){
                DynamicDataSourceContextHolder.setDataSourceKey(dataSource.value());
//                System.out.println("Switch DataSource to [" + DynamicDataSourceContextHolder.getDataSourceKey()
//                        + "] in Method [" + point.getSignature() + "]");
            }
        }
    }

    /**
     * 重置数据源
     * @param point
     * @param dataSource
     */
    @After("@annotation(dataSource))")
    public void restoreDataSource(JoinPoint point, DataSourceBy dataSource) {
        // 将数据源置为默认数据源
        DynamicDataSourceContextHolder.clearDataSourceKey();
//        System.out.println("Restore DataSource to [" + DynamicDataSourceContextHolder.getDataSourceKey()
//                + "] in Method [" + point.getSignature() + "]");
    }
}
